#!/usr/bin/env bash

set -euo pipefail

ARGS=@@ARGS@@
BUILDIFIER_SHORT_PATH=@@BUILDIFIER_SHORT_PATH@@
BUILDOZER_SHORT_PATH=@@BUILDOZER_SHORT_PATH@@
ERROR_ON_NO_CHANGES=@@ERROR_ON_NO_CHANGES@@
FORMAT_ON_WRITE=@@FORMAT_ON_WRITE@@

buildifier_short_path="$BUILDIFIER_SHORT_PATH"
buildozer_short_path=$(readlink "$BUILDOZER_SHORT_PATH")

if [[ "$FORMAT_ON_WRITE" == "true" ]]; then
    # If the `buildifier` attribute has a value, use it instead
    if [ -n "$buildifier_short_path" ]; then
        buildifier_short_path=$(readlink "$buildifier_short_path")
    fi

    ARGS+=("-buildifier=${buildifier_short_path}")
fi

cd "$BUILD_WORKSPACE_DIRECTORY"
set +e
"$buildozer_short_path" "${ARGS[@]}" "$@"
ret=$?
if [[ "$ret" -eq 3 && "$ERROR_ON_NO_CHANGES" == "false" ]]; then
    exit 0
else
    exit "$ret"
fi
